package com.yhy.common.exception;

import com.yhy.common.dto.AppReturnMsg;
import com.yhy.common.dto.ReturnCode;
import io.netty.util.internal.ThrowableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

    /**
     * 处理所有不可知的异常
     * @param e
     * @return
     */
    @org.springframework.web.bind.annotation.ExceptionHandler(Throwable.class)
    public AppReturnMsg handleException(Throwable e){
        // 打印堆栈信息
        LOGGER.error(ThrowableUtil.stackTraceToString(e));
        AppReturnMsg returnMsg = new AppReturnMsg(ReturnCode.FAIL_CODE.getCode(),e.getMessage() == null ? "异常错误:"+ThrowableUtil.stackTraceToString(e) : e.getMessage());
        return returnMsg;
    }

    /**
     * 处理自定义异常
     * @param e
     * @return
     */
	@org.springframework.web.bind.annotation.ExceptionHandler(value = BusinessException.class)
	public AppReturnMsg businessException(BusinessException e) {
        // 打印堆栈信息
        LOGGER.error(ThrowableUtil.stackTraceToString(e));
        AppReturnMsg returnMsg = new AppReturnMsg(ReturnCode.FAIL_CODE.getCode(),e.getMessage() == null ? "业务异常:"+ThrowableUtil.stackTraceToString(e) : e.getMessage());
        return returnMsg;
	}

}
